<?php

namespace App\Services\UserUpgrade;

use Carbon\Carbon;
use App\Models\User;
use Illuminate\Support\Facades\DB;

class UserUpgrade
{
	protected ?User $user = null;

    public function __construct(User $user)
    {
        $this->user = $user;
    }

	protected function execute(User $user)
	{
        if ($user->isNotValidVip()) return;



        DB::transaction(function () use ($user) {

             $userReason = "";
             $TeamReason = "";
             $data = [];
            
             $needGradeNumber = cs("sale")->auto_upgrade_needs_children;
            $needTeamNumber = cs("sale")->auto_upteam_needs_children;

             $userVipNumber = $user->myVipChildren()->count();
             $userTeamNumber = $user->myValidChildren()->count();

             $userLevel = intval($userVipNumber/$needGradeNumber);
             $teamLevel = intval($userTeamNumber/$needTeamNumber);

             if($userLevel > $user->user_level){
                 $userReason = "升级为{$userLevel}星会员";
                 $data['user_level'] = $userLevel;
                 if($userLevel == 2){

                    $user->update(['upgrade_at'=>Carbon::now()->subDays(cs('sale')->detect_days)]);
                 }

             }elseif($userLevel < $user->user_level){
                  $userReason = "降级为{$userLevel}星会员";
                  $data['user_level'] = $userLevel;
                  if($userLevel == 1 && $user->is_stop == 1){
                        $user->update(['is_stop'=>false]);
                  }

             }
             if($userReason){
                 $user->upgradeLogs()->create(['reason' => $userReason]);
                

             }

             if($teamLevel > $user->team_level){
                 $TeamReason = "升级为{$teamLevel}层团长";
                 $data['team_level'] = $teamLevel;

             }elseif($teamLevel < $user->team_level){
                  $TeamReason = "降级为{$teamLevel}层团长";
                  $data['team_level'] = $teamLevel;

             }
            
             if($TeamReason){
                 $user->upgradeLogs()->create(['reason' => $TeamReason]);
                

             }


             if($data){

                 $user->update($data);
             }

             if($user->parent){

                 user_upgrade($user->parent);
             }

          
        });

	}

	public function upgrade(User $user)
	{
		
		$this->execute($user);
	}
}
